/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
#include "Primitive.h"

#include "GL/gl.h"
#include "GL/glu.h"
#include "Object.h"
#include "World.h"
//#include "MaterialHandler.h"
#include "mathutils.h"
#include "owndebug.h"

CPrimitive::CPrimitive(CObject *ParentObject, dSpaceID SpaceID, 
                      dBodyID parentBodyID, const TMaterial *Material, bool IsStatic)
:ParentObject(ParentObject),
WorldID(ParentObject->WorldID),
SpaceID(SpaceID),
IsStatic(IsStatic),
NotifyCollisions(false),
Material(Material)
{
  GeomID=dCreateGeomTransform(SpaceID);
  //static means that geom has no body
  if (IsStatic)
  {
    this->BodyID=0;
    createdBody=false;
  } else { 
    if (parentBodyID==0 )
    {
      this->BodyID=dBodyCreate(this->WorldID);
      createdBody=true;
    } else {
      this->BodyID=parentBodyID;
      createdBody=false;
    }
    dGeomSetBody(this->GeomID, this->BodyID);
  }
  GeomData=new TGeomData;
  GeomData->Primitive=this;
  dGeomSetData(this->GeomID,GeomData);
  
}

CPrimitive::~CPrimitive()
{
  //if primitive's body was created in constructor delete it
  if (createdBody)
  {
    dBodyDestroy(this->BodyID);
  }
  dGeomDestroy(GeomID);
  delete GeomData;
}
    
void CPrimitive::GetBodyTransMatrix(dReal *M)
{
  ODEToOGL(dBodyGetRotation(this->BodyID), dBodyGetPosition(this->BodyID), M);
} 

void CPrimitive::GetGeomTransMatrix(dReal *M)
{
  ODEToOGL(dGeomGetRotation(this->GeomID), dGeomGetPosition(this->GeomID), M);
}

void CPrimitive::OnCollision(int numc, dContact *contacts, CPrimitive *primitive)
{
  if (this->NotifyCollisions)
    ParentObject->OnCollision(this,numc,contacts,primitive);
}
